package cn.qingfeng.a003_chat_v2_1.javafxview;

import cn.qingfeng.a003_chat_v2_1.message.ChatRequestMessage;
import cn.qingfeng.a003_chat_v2_1.message.LoginRequestMessage;
import io.netty.channel.Channel;
import javafx.fxml.FXML;
import javafx.scene.control.*;

public class QQDialogController {

    @FXML
    private ListView<String> messageListView;

    @FXML
    private TextArea inputTextArea;

    @FXML
    private TextField usernameTextField;

    @FXML
    private TextField targetTextField;

    @FXML
    private PasswordField passwordPasswordField;

    @FXML
    private Label resultLabel;

    private Channel channel;

    @FXML
    // 这个方法是自动调用的初始化方法，用于执行启动时的逻辑
    private void initialize() {
        System.out.println("init...............");
    }

    @FXML
    private void handleSendButtonClicked() {
        String currentUsername = usernameTextField.getText();
        String targetUsername = targetTextField.getText();
        String content = inputTextArea.getText();
        if (!content.trim().isEmpty()) {
            channel.writeAndFlush(new ChatRequestMessage("send", currentUsername, targetUsername, content));

            messageListView.getItems().add("我：" + content);
            inputTextArea.clear();
        }
    }

    @FXML
    private void handleLoginButtonClicked() throws InterruptedException {
        String username = usernameTextField.getText();
        String password = passwordPasswordField.getText();

        channel = ChatClientRenovation.init();
        channel.writeAndFlush(new LoginRequestMessage("login", username, password));
        System.out.println("请稍后...");

        try {
            ChatClientRenovation.WAIT_FOR_LOGIN.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (ChatClientRenovation.LOGIN_FLAG.get()) {
            resultLabel.setText("登录成功");
        } else {
            resultLabel.setText("登录失败--");
            channel.close();
        }
    }

    public void receiveContent(String content) {
        messageListView.getItems().add(content);
    }
}